import os
from flask import Flask
from datetime import timedelta
from flask_cors import CORS
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    CORS(app, supports_credentials=True)
    app.config.from_mapping(
        SECRET_KEY='dev',
    )
    # 设置 session 的有效期
    app.config['PERMANENT_SESSION_LIFETIME'] =  timedelta(hours=1)
    app.config.update(
        SESSION_COOKIE_SECURE=True,
        SESSION_COOKIE_HTTPONLY=True,
        SESSION_COOKIE_SAMESITE='None',
    )
    app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024  #上传最大为10MB

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    from . import db
    with app.app_context():
        db.init_app(app)

    from . import auth
    app.register_blueprint(auth.bp)

    from . import baidu_news
    app.register_blueprint(baidu_news.bp)

    from . import programs
    app.register_blueprint(programs.bp)

    from . import ai
    app.register_blueprint(ai.bp)

    from . import upload
    app.register_blueprint(upload.bp)

    return app
